import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/tab_model.dart';
import 'package:yysk_app/pages/nft_pages/order/order_detail/order_detail_page.dart';
import 'package:yysk_app/pages/nft_pages/order/order_detail/order_incubation_detail_page.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/widget/app_bar_back_widget.dart';
import 'package:yysk_app/widget/button_widget.dart';
import 'package:yysk_app/widget/custom_app_bar2.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/widget/lazy_network_image.dart';
import 'package:yysk_app/widget/refresh_and_scroll_widget.dart';
import 'package:yysk_app/widget/tab_widget.dart';
import 'package:oktoast/oktoast.dart';

import 'order_controller.dart';

class OrderPage extends GetView<OrderController> {
  static const String path = '/order';
  const OrderPage({super.key});

  @override
  Widget build(BuildContext context) {
    double top = MediaQuery.of(context).padding.top;
    return Scaffold(
      // backgroundColor: AppColors.backgroundColorGreyF2,
      body: Stack(
        children: [
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: ImageAssetWidget(
              width: 375.px,
              height: 812.px,
              imageUrl: 'static/images/bg.png',
            ),
          ),

          Container(
            // color: AppColors.backgroundColorBlack,
            child: Column(
              children: [
                Obx(() {
                  return Expanded(
                    child: Container(
                      padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
                      child: Column(
                        children: [
                          SizedBox(height: top),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Stack(
                                children: [
                                  CustomAppBar2(
                                    // backgroundColor: AppColors.backgroundColorEnd06,
                                    context: context,
                                    onBack: () {},
                                    title: '',
                                  ),
                                  Positioned(
                                    top: 0,
                                    bottom: 0,
                                    child: Center(
                                      child: TabWidget(
                                        value: controller.activeTab.value,
                                        isCurrentFontSize: 17,
                                        notCurrentFontSize: 17,
                                        rowMainAxisAlignment: 'center',
                                        activeColor: AppColors.fontColor,
                                        tabColor: AppColors.fontColorGray99,
                                        tabList: [
                                          TabModel(label: '购买订单', code: 'buy'),
                                          TabModel(label: '出售订单', code: 'sale'),
                                        ],
                                        onChanged: (val) {
                                          controller.changeTab(val);
                                        },
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                          hiSpace(height: 10.px),
                          controller.activeTab.value == 'buy'
                              ?
                              // Container(
                              //   height: 37.px,
                              //   width: context.width,
                              //   decoration: BoxDecoration(
                              //     borderRadius: BorderRadius.only(
                              //       topLeft: Radius.circular(18.px),
                              //       topRight: Radius.circular(18.px),
                              //     ),
                              //     gradient: LinearGradient(
                              //       colors: [
                              //         Color.fromRGBO(31, 33, 38, 1),
                              //         Color.fromRGBO(30, 33, 38, 0),
                              //       ],
                              //       begin: Alignment.topCenter,
                              //       end: Alignment.bottomCenter,
                              //     ),
                              //   ),
                              //   child:
                              TabWidget(
                                height: 37,
                                isCurrentFontSize: 14,
                                notCurrentFontSize: 14,
                                rowMainAxisAlignment: 'spaceBetween',
                                activeColor: AppColors.fontColorSearch,
                                tabColor: AppColors.fontColorGray99,
                                showDefalutTab: true,
                                crossAxisSpacing: 0,
                                tabList: [
                                  TabModel(
                                    label: '藏品发售',
                                    code: 'product',
                                    bySelf: true,
                                    child: _tabChildrenWidget(
                                      txt: '藏品发售',
                                      context: context,
                                      code: 'product',
                                    ),
                                  ),
                                  TabModel(
                                    code: 'incubation',
                                    label: '品牌孵化',
                                    bySelf: true,
                                    child: _tabChildrenWidget(
                                      txt: '品牌孵化',
                                      context: context,
                                      code: 'incubation',
                                    ),
                                  ),
                                ],
                                onChanged: (val) {
                                  controller.changeBuyTabStatus(val);
                                },
                                // ),
                              )
                              : SizedBox(),
                          // hiSpace(height: 10.px),
                          controller.activeTab.value == 'sale'
                              ?
                              // Container(
                              //   height: 37.px,
                              //   width: context.width,
                              //   decoration: BoxDecoration(
                              //     borderRadius: BorderRadius.only(
                              //       topLeft: Radius.circular(18.px),
                              //       topRight: Radius.circular(18.px),
                              //     ),
                              //     gradient: LinearGradient(
                              //       colors: [
                              //         Color.fromRGBO(31, 33, 38, 1),
                              //         Color.fromRGBO(30, 33, 38, 0),
                              //       ],
                              //       begin: Alignment.topCenter,
                              //       end: Alignment.bottomCenter,
                              //     ),
                              //   ),
                              //   child:
                              TabWidget(
                                height: 37,
                                isCurrentFontSize: 14,
                                notCurrentFontSize: 14,
                                rowMainAxisAlignment: 'spaceBetween',
                                activeColor: AppColors.fontColorSearch,
                                tabColor: AppColors.fontColorGray99,
                                showDefalutTab: true,
                                crossAxisSpacing: 0,
                                tabList: [
                                  TabModel(
                                    code: 'sale',
                                    label: '品牌孵化',
                                    bySelf: true,
                                    child: _tabChildrenWidget(
                                      txt: '品牌孵化',
                                      context: context,
                                      code: 'sale',
                                    ),
                                  ),
                                ],
                                onChanged: (val) {
                                  controller.changeTab(val);
                                  controller.changeBuyTabStatus('incubation');
                                },
                              )
                              // )
                              : SizedBox(),
                          hiSpace(height: 10.px),
                          controller.activeTab.value == 'buy'
                              ? Container(
                                padding: EdgeInsets.symmetric(
                                  horizontal: 12.px,
                                ),
                                child: TabWidget(
                                  value: controller.statusCode.value,
                                  isCurrentFontSize: 12,
                                  notCurrentFontSize: 12,
                                  height: 30,
                                  activeColor: AppColors.fontColorBlack12,
                                  tabColor: AppColors.fontColorGray99,
                                  activeBgColor:
                                      AppColors.backgroundColorBlackE2,
                                  tabBgColor: AppColors.backgroundColorGrey2,
                                  showTabBgLinearColor: true,
                                  // rowMainAxisAlignment: 'spaceAround',
                                  crossAxisSpacing: 8,
                                  tabList: [
                                    TabModel(label: '全部', code: ''),
                                    TabModel(label: '待付款', code: '0'),
                                    TabModel(label: '已完成', code: '10'),
                                    TabModel(label: '已关闭', code: '20'),
                                  ],
                                  onChanged: (val) {
                                    controller.changeBuyTypeStatus(val);
                                  },
                                ),
                              )
                              : SizedBox(),
                          controller.activeTab.value == 'sale'
                              ? Container(
                                padding: EdgeInsets.symmetric(
                                  horizontal: 12.px,
                                ),
                                child: TabWidget(
                                  isCurrentFontSize: 12,
                                  notCurrentFontSize: 12,
                                  height: 30,
                                  activeColor: AppColors.fontColorBlack12,
                                  tabColor: AppColors.fontColorGray99,
                                  activeBgColor:
                                      AppColors.backgroundColorBlackE2,
                                  tabBgColor: AppColors.backgroundColorGrey2,
                                  showTabBgLinearColor: true,
                                  // rowMainAxisAlignment: 'spaceAround',
                                  crossAxisSpacing: 8,
                                  tabList: [
                                    TabModel(label: '已锁单', code: '0'),
                                    TabModel(label: '已售出', code: '10'),
                                    TabModel(label: '已取消', code: '20'),
                                  ],
                                  onChanged: (val) {
                                    controller.changeSaleTypeStatus(val);
                                  },
                                ),
                              )
                              : SizedBox(),
                          controller.activeTab.value == 'buy'
                              ? (controller.buyTabCode.value == 'product'
                                  ? Expanded(
                                    child: Container(
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(
                                          6.px,
                                        ),
                                      ),
                                      padding: EdgeInsets.fromLTRB(
                                        12,
                                        10,
                                        12,
                                        0,
                                      ),
                                      child: RefreshAndScrollWidget(
                                        onRefresh: _handleRefresh,
                                        scrollController:
                                            controller.buyScrollController,
                                        itemBuilder:
                                            (item, index) => _buildItem(
                                              item: item,
                                              context: context,
                                            ),
                                        itemCount:
                                            controller.orderBuyList.length,
                                        items: controller.orderBuyList,
                                        emptyText: '暂无订单~',
                                      ),
                                    ),
                                  )
                                  : Expanded(
                                    child: Container(
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(
                                          6.px,
                                        ),
                                      ),
                                      padding: EdgeInsets.fromLTRB(
                                        12,
                                        10,
                                        12,
                                        0,
                                      ),
                                      child: RefreshAndScrollWidget(
                                        onRefresh: _handleRefresh,
                                        scrollController:
                                            controller
                                                .buyIncubationScrollController,
                                        itemBuilder:
                                            (item, index) => _buildItem(
                                              item: item,
                                              context: context,
                                            ),
                                        itemCount:
                                            controller
                                                .orderBuyIncubationList
                                                .length,
                                        items:
                                            controller.orderBuyIncubationList,
                                        emptyText: '暂无订单~',
                                      ),
                                    ),
                                  ))
                              : SizedBox(),
                          controller.activeTab.value == 'sale'
                              ? Expanded(
                                child: Container(
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(6.px),
                                  ),
                                  padding: EdgeInsets.fromLTRB(12, 10, 12, 0),
                                  child: RefreshAndScrollWidget(
                                    onRefresh: _handleRefresh,
                                    scrollController:
                                        controller.saleScrollController,
                                    itemBuilder:
                                        (item, index) => _buildItem(
                                          item: item,
                                          context: context,
                                        ),
                                    itemCount: controller.orderSaleList.length,
                                    items: controller.orderSaleList,
                                    emptyText: '暂无订单~',
                                  ),
                                ),
                              )
                              : SizedBox(),
                        ],
                      ),
                    ),
                  );
                }),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // order
  Widget _buildOrderCollectionInfoOrder({required item}) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Row(
          children: [
            LazyImage(
              imageUrl: '${item.coverImageUrl}',
              width: 44.px,
              height: 44.px,
              borderRadius: 6.px,
            ),
            hiSpace(width: 10.px),
            SizedBox(
              height: 48.px,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    constraints: BoxConstraints(maxWidth: 210.px),
                    child: Text(
                      '${item.collectionName}',
                      style: TextStyle(
                        fontSize: 14.px,
                        color: AppColors.fontColor,
                      ),
                      overflow: TextOverflow.ellipsis,
                      textAlign: TextAlign.left,
                    ),
                  ),
                  hiSpace(height: 7.px),
                  Container(
                    constraints: BoxConstraints(maxWidth: 210.px),
                    child: Text(
                      '${item.daoName}',
                      style: TextStyle(
                        fontSize: 12.px,
                        color: AppColors.fontColorGray99,
                      ),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
        SizedBox(
          height: 48.px,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(
                controller.activeTab.value == 'buy' &&
                        controller.buyTabCode.value == 'product'
                    ? 'x ${item.count}'
                    : '#${item.tokenId}',
                style: TextStyle(
                  fontSize: 12.px,
                  color: AppColors.fontColorGray99,
                ),
              ),
              Text(
                '￥${item.payPrice}',
                style: TextStyle(color: AppColors.fontColor, fontSize: 14.px),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildItem({required item, required BuildContext context}) {
    return GestureDetector(
      onTap: () {
        String type;
        String path;
        if (controller.activeTab.value == 'buy' &&
            controller.buyTabCode.value == 'product') {
          type = 'buy'; // 购买首发订单
          path = OrderDetailPage.path;
        } else if (controller.activeTab.value == 'sale') {
          type = 'sale'; // 售出孵化订单
          path = OrderIncubationDetailPage.path;
        } else {
          type = 'buyIn'; // 购买孵化订单
          path = OrderIncubationDetailPage.path;
        }
        Get.toNamed(
          '$path?id=${item.id}&type=$type',
          arguments: {'id': item.id, 'type': type},
        );
      },
      child: Container(
        margin: EdgeInsets.only(bottom: 12.px),
        decoration: BoxDecoration(
          color: AppColors.backgroundColorBlackLight,
          borderRadius: BorderRadius.circular(10.px),
        ),
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.all(12.px),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(10.px),
                  topRight: Radius.circular(10.px),
                ),
              ),
              child: Column(
                children: [
                  _buildOrderCollectionInfoOrder(item: item),
                  hiSpace(height: 12.px),
                  Padding(
                    padding: EdgeInsets.only(left: 54.px),
                    child: Column(
                      children: [
                        Container(
                          height: 1.px,
                          color: AppColors.backgroundColorGreyF8,
                        ),
                        hiSpace(height: 12.px),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '创建时间',
                              style: TextStyle(
                                fontSize: 12.px,
                                color: AppColors.fontColorGray99,
                              ),
                            ),
                            Text(
                              '${item.createTime}',
                              style: TextStyle(
                                fontSize: 12.px,
                                color: AppColors.fontColorGrayE8,
                              ),
                            ),
                          ],
                        ),
                        hiSpace(height: 12.px),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '订单编号',
                              style: TextStyle(
                                fontSize: 12,
                                color: AppColors.fontColorGray99,
                              ),
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                SizedBox(
                                  width: 150.px,
                                  child: Text(
                                    '${item.orderCode}',
                                    style: TextStyle(
                                      fontSize: 12.px,
                                      color: AppColors.fontColor,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ),
                                ),
                                GestureDetector(
                                  onTap: () {
                                    Clipboard.setData(
                                      ClipboardData(
                                        text: '${item.orderCode}' ?? '暂无数据',
                                      ),
                                    );
                                    showToast('复制成功');
                                  },
                                  child: ImageAssetWidget(
                                    imageUrl: 'static/images/mine/copy.png',
                                    width: 12.px,
                                    height: 12.px,
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                        item.orderStatus == 'WAITING_PAY' &&
                                controller.activeTab.value == 'buy'
                            ? hiSpace(height: 20.px)
                            : SizedBox(),
                        item.orderStatus == 'WAITING_PAY' &&
                                controller.activeTab.value == 'buy'
                            ? Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                ButtonWidget(
                                  label: '取消订单',
                                  width: 75.px,
                                  height: 23.px,
                                  fontSize: 12,
                                  borderRadius: 6,
                                  fontColor: AppColors.fontColorBlack,
                                  bgColorStart: AppColors.fontColorB2,
                                  bgColorEnd: AppColors.fontColorB2,
                                  onPressed: () {
                                    _showCancleSheet(
                                      context: context,
                                      id: item.id,
                                    );
                                  },
                                ),
                                hiSpace(width: 11.px),
                                ButtonWidget(
                                  label: '去支付',
                                  width: 60.px,
                                  height: 23.px,
                                  fontSize: 12,
                                  borderRadius: 6,
                                  fontColor: AppColors.fontColorBlack,
                                  onPressed: () {
                                    controller.payToken(
                                      item.id,
                                      item.productType,
                                    );
                                    // Get.toNamed(ConfirmPaymentPage.path);
                                  },
                                ),
                              ],
                            )
                            : SizedBox(),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  _buildOrderStatus(item) {
    switch (item.orderStatus) {
      case 'WAITING_PAY':
        return '待支付';
      case 'PAYING':
        return '支付中';
      case 'PAY_SUCCESS':
        return '已完成';
      case 'CANCELLED':
        return '已取消';
      case 'PAY_TIMEOUT':
        return '已取消';
      case 'FAILED':
        return '已取消';
      default:
        return '';
    }
  }

  _tabChildrenWidget({
    required String txt,
    required BuildContext context,
    required String code,
  }) {
    return Container(
      // constraints: BoxConstraints(minWidth: 72.px),
      height: 37.px,
      padding: EdgeInsets.only(top: 8.px),
      width:
          controller.activeTab.value == 'sale'
              ? context.width
              : context.width / 2,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            txt,
            style: TextStyle(
              fontWeight: FontWeight.w500,
              fontSize: 14.px,
              color:
                  controller.buyTabCode.value == code ||
                          controller.activeTab.value == 'sale'
                      ? AppColors.fontColorSearch
                      : AppColors.fontColorGray99, // 注意：这里颜色必须是不透明的，否则会被覆盖
            ),
          ),
          Container(
            width:
                controller.activeTab.value == 'sale'
                    ? context.width
                    : context.width / 2,
            height: 1.px,
            color:
                controller.buyTabCode.value == code ||
                        controller.activeTab.value == 'sale'
                    ? AppColors.fontColorSearch
                    : AppColors.fontColorGray99,
          ),
        ],
      ),
    );
  }

  Future<void> _handleRefresh() async {
    if (controller.activeTab.value == 'buy') {
      if (controller.buyTabCode == 'product') {
        await controller.getBuyProductOrder();
      } else {
        await controller.getBuyIncubationOrder();
      }
    } else if (controller.activeTab.value == 'sale') {
      await controller.getSaleOrder();
    }
    return;
  }

  _showCancleSheet({required BuildContext context, required int id}) {
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          backgroundColor: AppColors.backgroundColorBlackLight,
          child: Padding(
            padding: EdgeInsets.fromLTRB(22.px, 22.px, 22.px, 16.px),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Center(
                  child: Text(
                    '温馨提示',
                    style: TextStyle(
                      fontSize: 20.px,
                      color: AppColors.fontColor,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
                hiSpace(height: 16.px),
                Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    '为维护市场秩序，请尽快完成支付。',
                    style: TextStyle(
                      fontSize: 16.px,
                      color: AppColors.fontColor,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
                hiSpace(height: 12.px),
                Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    '当天下单3次未支付，系统会判断为恶意锁单，并限制您当天继续交易，以示惩戒。',
                    style: TextStyle(
                      fontSize: 16.px,
                      color: AppColors.fontColor,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
                hiSpace(height: 12.px),
                Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    '3小时后自动解除限制，情节严重者，平台有权对其账号永久封禁。',
                    style: TextStyle(
                      fontSize: 16.px,
                      color: AppColors.fontColor,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
                hiSpace(height: 36.px),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    ButtonWidget(
                      label: '不取消',
                      width: 111.px,
                      height: 36.px,
                      fontSize: 14.px,
                      bgColorStart: AppColors.backgroundColorGreyF8,
                      bgColorEnd: AppColors.backgroundColorGreyF8,
                      fontColor: AppColors.fontColor,
                      borderRadius: 18,
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    ),
                    ButtonWidget(
                      label: '确认取消',
                      width: 111.px,
                      height: 36.px,
                      fontSize: 14.px,
                      onPressed: () {
                        controller.cancelOrder(id);
                      },
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
